<template>
	<cl-drawer
		ref="drawer"
		:props="{
			title: `${editing ? '编辑' : '新增'}事业部`,
			size: '690px'
		}"
		show-confirm
		confirm-text="提交"
		@close="reset"
		@confirm="submit"
		:saving="saving"
	>
		<el-form ref="form" :model="form" :rules="rules" label-position="top" :disabled="saving">
			<el-form-item label="基本信息">
				<el-card shadow="never">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="事业部名称" prop="biz_name">
								<el-input v-model="form.biz_name" placeholder="请填写事业部名称" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="联系人" prop="biz_contact">
								<el-input
									v-model="form.biz_contact"
									placeholder="请填写联系人名称"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="联系电话" prop="biz_mobile">
								<el-input
									v-model="form.biz_mobile"
									placeholder="请填写联系电话"
									maxlength="11"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="所在地区" prop="region">
								<cl-cascader
									v-model="form.region"
									:options="addressLevel"
									placeholder="请选择省市区"
									style="width: 100%"
									filterable
								/>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="详细地址" prop="biz_detail_addr">
								<el-input
									v-model="form.biz_detail_addr"
									placeholder="请填写详细地址"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="经营类目" prop="tids">
								<cl-select
									v-model="form.tids"
									filterable
									multiple
									placeholder="请选择经营类目"
									style="width: 100%"
								>
									<el-option
										v-for="item in cateList"
										:key="item.id"
										:label="item.tname"
										:value="item.id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="事业部Logo" prop="biz_logo">
								<cl-upload v-model="form.biz_logo" />
								<div class="tips">建议尺寸200x200px</div>
							</el-form-item>
						</el-col>
						<el-col :span="16">
							<el-form-item label="营业时间" prop="office_time">
								<div class="flex">
									<el-time-select
										placeholder="起始时间"
										v-model="form.cart_stime"
										:clearable="false"
										:picker-options="{
											start: '00:00',
											step: '00:30',
											end: '23:30'
										}"
										@change="changeBtime"
									>
									</el-time-select>
									<span style="margin:0 6px;">~</span>
									<el-time-select
										ref="etime"
										placeholder="结束时间"
										v-model="form.cart_etime"
										:clearable="false"
										:picker-options="{
											start: '00:00',
											step: '00:30',
											end: '23:30',
											minTime: form.cart_stime
										}"
									>
									</el-time-select>
								</div>
							</el-form-item>
						</el-col>
					</el-row>
				</el-card>
			</el-form-item>
			<el-form-item prop="mange_brands">
				<template #label>
					经营品牌
					<el-button type="text" icon="el-icon-circle-plus" @click="addBrand">
						新增品牌
					</el-button>
				</template>
				<el-card shadow="never">
					<el-transfer
						filterable
						filter-placeholder="请输入搜素内容"
						v-model="form.mange_brands"
						:data="brands"
						:props="{
							key: 'bra_id',
							label: 'bra_name'
						}"
						:titles="['品牌', '已选']"
						@change="braChange"
					/>
				</el-card>
			</el-form-item>
			<el-form-item label="设置主品牌" required v-if="form.mange_brands.length">
				<el-card shadow="never">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="主品牌" prop="main_brands">
								<cl-select
									v-model="form.main_brands"
									filterable
									placeholder="请选择主品牌"
									style="width: 100%"
									@change="mainBraChange"
								>
									<el-option
										v-for="item in form.brand"
										:key="item.bra_id"
										:label="item.bra_name"
										:value="item.bra_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
					</el-row>
				</el-card>
			</el-form-item>
			
		</el-form>
		<cl-brand-form ref="brandForm" @confirm="getBrands" />
	</cl-drawer>
</template>
<script>
import { mapState, mapActions } from "vuex";
import { validate } from "@/utils/validate";
import threeLevel from "@/assets/countryLevel3";
import dayjs from "dayjs";

export default {
	name: "business-form",
	data() {
		const profitRatioValidator = (rule, value, callback) => {
			if (value > 100 || value <= 0) {
				return callback(new Error("分润比例不能大于100"));
			}
			return callback();
		};
		const validateOfficeTime = (rule, value, callback) => {
			const { cart_stime, cart_etime } = this.form;
			if (!cart_stime) {
				return callback(new Error("请选择营业开始时间"));
			}
			if (!cart_etime) {
				return callback(new Error("请选择营业结束时间"));
			}
			callback();
		};
		return {
			addressLevel: threeLevel,
			editing: false,
			saving: false,
			form: {
				biz_id: undefined,
				biz_name: "", //事业部名称
				biz_contact: "", //联系人名称
				biz_mobile: "", //联系人电话
				biz_logo: "",
				region: [],
				biz_addr: "", //省id，市id，区id
				biz_detail_addr: "", //详细地址
				referee_phone: "", //推荐人电话
				tids: [],
				tid: "", //主营类目id
				tname: "", //主营类目名称
				mange_brands: [],
				brand: [],
				main_brands: "",
				cart_stime: "10:00",
				cart_etime: "20:00"
			},
			main_bra: {},
			rules: {
				biz_name: [{ required: true, message: "请填写事业部名称" }],
				biz_contact: [{ required: true, message: "请填写联系人名称" }],
				biz_mobile: [
					{ required: true, message: "请填写联系电话" },
					{ pattern: validate.mobile, message: "联系电话格式不正确" }
				],
				region: [{ required: true, message: "请选择所在地区" }],
				biz_detail_addr: [{ required: true, message: "请填写详细地址" }],
				tids: [{ required: true, message: "请选择经营类目" }],
				mange_brands: [{ required: true, message: "请选择经营品牌" }],
				main_brands: [{ required: true, message: "请选择主品牌" }],
				profit_ratio: [
					{ required: true, type: "number", message: "请填写分润比例" },
					// { validator: profitRatioValidator },
					{ max: 100, type: "number", message: "分润比例不能大于100" }
				],
				office_time: [{ required: true, validator: validateOfficeTime }]
			},
			cateList: []
		};
	},
	computed: {
		...mapState("common", ["brands"])
	},
	created() {
		const { biz_id } = this.userInfo;
		this.form.biz_id = biz_id;
		this.getCateList();
	},
	methods: {
		...mapActions("common", ["getBrands"]),
		open(editing = false, data = {}) {
			this.$refs.drawer.create(() => {
				this.editing = editing;
				this.getBrands();
				if (!editing) return;
				Object.keys(this.form).forEach(key => {
					data[key] != undefined && (this.form[key] = data[key]);
				});
				data.biz_addr && (this.form.region = data.biz_addr.split(","));
				data.tid && (this.form.tids = data.tid.split(",").map(Number));
				this.form.mange_brands = [];
				if (data?.mange_brands != "-") {
					this.form.mange_brands = (data?.mange_brands ?? []).map(Number);
				}
				this.braChange();
				
			});
		},
		close() {
			this.$refs.drawer.close();
		},
		reset() {
			this.$resetFields(this.form);
			this.form.cart_stime = "10:00";
			this.form.cart_etime = "20:00";

			this.$refs.form.resetFields();
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				const { editing } = this;
				const { biz_id, brand, mange_brands, tids, region, ...args } = this.form;
				let form = {
					...args,
					biz_addr: region.join(),
					tid: tids.join(),
					tname: this.cateList
						.filter(v => tids.includes(v.id))
						.map(v => v.tname)
						.join(),
					mange_brands: mange_brands.join()
				};
				if (biz_id) {
					form.biz_id = biz_id;
				}

				this.saving = true;
				const res = await this.$service.business[editing ? "update" : "add"](form).done(
					() => {
						this.saving = false;
					}
				);
				this.$message.success(`${editing ? "修改" : "新增"}成功`);
				this.$emit("confirm", editing ? false : true);
				this.close();
				await this.getBizList();
				await this.getBizRefBrand(res.biz_id);
			});
		},
		// 获取经营类目
		async getCateList() {
			const { lists = [] } = await this.$service.business.category();
			this.cateList = lists;
		},
		//新增品牌
		addBrand() {
			this.$refs.brandForm.open();
		},
		// 经营品牌变化
		braChange() {
			const { mange_brands, main_brands } = this.form;
			this.form.brand = this.brands
				.filter(v => mange_brands.includes(v.bra_id))
				.map(v => ({
					...v,
					profit_ratio: v.profit_ratio ?? 10
				}));
			if (!mange_brands.includes(main_brands)) {
				this.form.main_brands = "";
			}
			this.mainBraChange();
		},
		//主品牌
		mainBraChange() {
			const { main_brands } = this.form;
			if (!main_brands) {
				this.main_bra = {};
				
				return;
			}
			this.main_bra = this.form.brand.find(v => v.bra_id == main_brands) || {};
			
		},
		// 营业开始时间改动
		changeBtime() {
			this.$refs.etime?.focus?.();
			if (!this.form.cart_stime || !this.form.cart_etime) return;
			let date = dayjs().format("YYYY-MM-DD");
			let btime = dayjs(date + " " + this.form.cart_stime);
			let etime = dayjs(date + " " + this.form.cart_etime);
			let diff = etime.diff(btime);
			if (diff > 0) return;
			this.form.cart_etime = "";
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep {
	.el-table {
		.el-form-item {
			margin-bottom: 0 !important;
		}
	}
}
.tips {
	color: #909399;
	font-size: 12px;
	line-height: 1.5;
}
</style>
